package com.ruoyi.common.utils.pdf;


import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.properties.TextAlignment;
import com.ruoyi.archives.domain.CanteenArea;
import com.ruoyi.archives.domain.EmerHandle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PdfExporter<T> {

    public void exportListToPdf(List<T> listItems, OutputStream outputStream) throws Exception {


        PdfWriter writer = new PdfWriter(outputStream);
        PdfDocument pdf = new PdfDocument(writer);
        Document document = new Document(pdf);
        try {
            PdfFont font = PdfFontFactory.createFont("D:/ruoyi/uploadPath/pdf/simsun.ttf");


            for (T obj : listItems) {
                List<Field> subFields = FieldUtils.getFieldsListWithAnnotation(obj.getClass(), Excel.class);
                for (Field subField : subFields) {
                    subField.setAccessible(true);
                    Excel attr = subField.getAnnotation(Excel.class);
                    Object value = getTargetValue(obj, subField, attr);
                    if (attr.cellType() == Excel.ColumnType.IMAGE) {
                        // 添加文本
                        Paragraph paragraph = new Paragraph(attr.name() + ":").setFont(font).setTextAlignment(TextAlignment.LEFT);
                        document.add(paragraph);
                        // 添加图片
                        // 从网络路径下载图片
                        ImageData imageData = null;
                        if (obj instanceof CanteenArea || obj instanceof EmerHandle) {
                            if (value != null && !"".equals(value)) {
                                for (String imgUrl : Convert.toStr(value).split(",")) {
                                    imageData = ImageDataFactory.create(downloadImageFromUrl(imgUrl));
                                    Image img = new Image(imageData);
                                    img.scale(0.5f, 0.5f);
                                    document.add(img);
                                }
                            }
                        } else {
                            if (value != null && !"".equals(value)) {
                                if (Convert.toStr(value).contains("http://")) {
                                    imageData = ImageDataFactory.create(downloadImageFromUrl(Convert.toStr(value)));
                                } else {
                                    imageData = ImageDataFactory.create(downloadImageFromUrl("http://53796ba3.cpolar.top" + Convert.toStr(value)));
                                }
                                Image img = new Image(imageData);
                                img.scale(0.5f, 0.5f);
                                document.add(img);
                            }
                        }
                    } else {
                        if (value != null && !"".equals(value)) {
                            String text = attr.name() + ":";
                            if (!attr.dateFormat().isEmpty()) {
                                text += DateUtils.parseDateToStr(attr.dateFormat(), (Date) value);
                            } else {
                                text += Convert.toStr(value);
                            }
                            // 添加文本
                            Paragraph paragraph = new Paragraph(text).setFont(font).setTextAlignment(TextAlignment.LEFT);
                            document.add(paragraph);
                        }
                    }
                }

                // 可选：添加一些空间以分隔条目
                document.add(new Paragraph("---------------------------------------------------------------------------------------").setFont(font).setTextAlignment(TextAlignment.LEFT));
            }

            document.close();
            System.out.println("PDF created successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Object getTargetValue(T vo, Field field, Excel excel) throws Exception {
        Object o = field.get(vo);
        if (StringUtils.isNotEmpty(excel.targetAttr())) {
            String target = excel.targetAttr();
            if (target.contains(".")) {
                String[] targets = target.split("[.]");
                for (String name : targets) {
                    o = getValue(o, name);
                }
            } else {
                o = getValue(o, target);
            }
        }
        return o;
    }

    public Object getValue(Object o, String name) throws Exception {
        if (StringUtils.isNotNull(o) && StringUtils.isNotEmpty(name)) {
            Class<?> clazz = o.getClass();
            Field field = clazz.getDeclaredField(name);
            field.setAccessible(true);
            o = field.get(o);
        }
        return o;
    }

    private byte[] downloadImageFromUrl(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (InputStream is = url.openStream()) {
            byte[] byteChunk = new byte[4096];
            int n;
            while ((n = is.read(byteChunk)) > 0) {
                baos.write(byteChunk, 0, n);
            }
        }
        return baos.toByteArray();
    }


}
